<?php


namespace App\Resource\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Constants\Stakeholder;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\Resource\Model\ShopModel;
use App\Resource\Model\TeamLeaderModel;
use App\Resource\Request\ShopRequest;
use App\Resource\Request\TeamLeaderRequest;
use App\Resource\Service\ShopService;
use App\Resource\Service\TeamLeaderService;
use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Rule;

/**
 * @Controller()
 */
class TeamLeaderController extends AbstractController
{

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var TeamLeaderService
     */
    private $teamLeaderService;

    /**
     * @Inject()
     * @var ShopService
     */
    private $shop;

    /**
     * 后台团长列表
     * @RequestMapping(path="/v1/teamLeader", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['id', 'name', 'delivery_address', 'detail_address', 'longitude', 'latitude', 'phone', 'shop_id', 'status', 'created_at'];
        $res = $this->teamLeaderService->getList($params, $perPage, $field);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 团长详情
     * @RequestMapping(path="/v1/teamLeader/{id:\d+}", methods="get")
     * @param int $id
     * @param RequestInterface $request
     *
     * @return array
     */
    public function info(int $id)
    {
        $field = ['id', 'name', 'delivery_address', 'detail_address', 'longitude', 'latitude', 'phone', 'shop_id', 'status', 'reject_reason', 'created_at', 'passing_time','approver'];
        $res = $this->teamLeaderService->getInfoById($id, $field);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 小程序端申请团长
     * @PostMapping(path="/v1/api/teamLeader/apply", methods="post")
     * @param ShopRequest $request
     *
     * @return array
     */
    public function apply(TeamLeaderRequest $request)
    {
        $params = $request->validated();
        $res = $this->teamLeaderService->apply($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 团长审核操作
     * @PutMapping(path="/v1/teamLeader/check", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function check(RequestInterface $request)
    {
        $params = $request->all();
        $validator = $this->validationFactory->make(
            $params,
            [
                'id' => 'required|integer',
                'name' => 'required',
                'delivery_address' => 'required',
                'detail_address' => 'required',
                'longitude' => 'required',
                'latitude' => 'required',
                'phone' => ['required', 'integer', Rule::unique('hf_team_leader')->ignore($params['id'])],
                'shop_id' => 'required|integer',
                'status' => 'required',
                'reject_reason' => 'sometimes|max:150',
                'approver' => 'sometimes',
            ],
            [],
            [
                'name' => '姓名',
                'delivery_address' => '小区/自提点',
                'detail_address' => '街道、门牌号',
                'longitude' => '经度',
                'latitude' => '纬度',
                'phone' => '手机号码',
                'shop_id' => '绑定店铺',
                'status' => '审核状态',
                'reject_reason' => '驳回原因',
                'approver' => '审批人',
            ]
        );
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            return $this->failed(ErrorCode::PARAMS_INVALID, $errorMessage);
        }
        $id = $params['id'];
        // 审核返回状态，有驳回和歇业两种
        $status = in_array($params['status'], [Stakeholder::LEADER_STATUS_REJECTED, Stakeholder::LEADER_STATUS_OUT_OF_BUSINESS]) ? $params['status'] : '';
        if (!$id || !$status) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        //若为驳回操作，需要填写驳回原因
        if ($status == Stakeholder::LEADER_STATUS_REJECTED && !trim($params['reject_reason'])) {
            return $this->failed(ErrorCode::TEAMLEADE_STATUS_REJECT);
        }
        //若为通过操作，需要加上通过时间
        if ($status == Stakeholder::LEADER_STATUS_OUT_OF_BUSINESS) {
            $params['passing_time'] = date('Y-m-d H:i;s', time());
        }

        $res = $this->teamLeaderService->check($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 团长编辑操作
     * @PutMapping(path="/v1/teamLeader/{id:\d+}", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param TeamLeaderRequest $request
     *
     * @return array
     */
    public function edit(int $id, TeamLeaderRequest $request)
    {
        $params = $request->validated();
        // 状态的修改，只能是营业和未营业两种
        if (!in_array($params['status'], [Stakeholder::LEADER_STATUS_IN_BUSINESS, Stakeholder::LEADER_STATUS_OUT_OF_BUSINESS])) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $res = $this->teamLeaderService->edit($id, $params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 退佣金
     *
     * @PostMapping(path="/v1/api/team_leader/back_commission", methods="post")
     * @param TeamLeaderRequest $request
     *
     * @return array
     */
    public function backCommission(RequestInterface $request)
    {
        $order_no = $request->input('order_no');
        if (!$order_no) {
            $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $leader_id = $request->input('leader_id');
        if (!$leader_id) {
            $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $commission = $request->input('commission', 0);
        $res = $this->teamLeaderService->backCommission($order_no, $leader_id, $commission);
        if ($res['code']) {
            return $this->failed($res['code'], $res['msg']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 团长中心
     *
     * @RequestMapping(path="/v1/api/team_lader/center/{id:\d+}", methods="get")
     *
     * @param int $id
     * @return array
     */
    public function center($id)
    {
        $_today = Carbon::today()->toDateString();
        $frozen_order_commission = $this->teamLeaderService->getFreezeOrderCommission($id);
        $filed = [
            Db::raw("convert((commission_amount - frozen_amount - $frozen_order_commission) / 100,decimal(15,2)) as balance"),
            Db::raw("convert((add_up_commission) / 100,decimal(15,2)) as add_up_commission")
        ];

        $leaderInfo = $this->teamLeaderService->getInfoById($id, $filed);

        // 今日交易数据
        $today = $this->shop->getDateShopWriteTrading($_today, $id, 2);
        // 当月交易佣金
        $dates = $this->teamLeaderService->prDates(date('Y-m-01'), date('Y-m-t'));
        $month = $this->shop->getDateShopWriteTrading($dates, $id, 2);

        $todayData = $this->teamLeaderService->getDayWriteOffOrder($id, $_today);

        $result = [
            // 今日佣金
            'today_commission'      => $today['commission'],
            // 当月佣金
            'last_month_commission' => $month['commission'],
            // 累计佣金
            'add_up_commission'     => $leaderInfo['data']['add_up_commission'] ?? 0,
            // 可提现金额
            'balance'               => $leaderInfo['data']['balance'] ?? 0,
            // 待自提数量
            'wait_takeaway_num'     => $this->teamLeaderService->wait_takeaway_num($id),
            // 销售数据
            'sales_data'            => $todayData,
        ];

        return $this->success($result, '获取团长中心信息成功');
    }

    /**
     * 提现
     *
     * @RequestMapping(path="/v1/api/team_lader/withdraw/{id:\d+}", methods="get,post")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function withdraw(int $id, RequestInterface $request)
    {
        try {
            if ($request->isMethod('get')) {
                $frozen_order_commission = $this->teamLeaderService->getFreezeOrderCommission($id);
                $filed = [
                    Db::raw("round((commission_amount - frozen_amount - $frozen_order_commission) / 100,2) as balance"),
                    'account_name',
                    'account_bank',
                    'bank_card_number',
                ];
                $info = $this->teamLeaderService->getInfoById($id, $filed);
                return $this->success(($info['data'] ?? []), '获取提现信息成功');
            }
            $amount = $request->input('withdraw_amount');
            $rules = [
                'withdraw_amount' => 'required|numeric',
            ];
            $message = [
                'withdraw_amount.required' => '请输入提现金额',
                'withdraw_amount.numeric' => '提现金额必须为数值',
            ];
            $validator = $this->validationFactory->make(['withdraw_amount' => $amount], $rules, $message);
            if ($validator->fails()) {
                $errorMessage = $validator->errors()->first();
                throw new \Exception($errorMessage, ErrorCode::PARAMS_INVALID);
            }
            $res = $this->teamLeaderService->withdraw($id, $amount);
            if (!$res['success']) {
                throw new \Exception($res['msg'], ErrorCode::SYSTEM_INVALID);
            }
            return $this->success('', '操作成功');
        } catch (\Exception $e) {
            return $this->failed($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 获取银行列表
     *
     * @RequestMapping(path="/v1/api/banks", methods="get")
     *
     * @return array
     */
    public function getBanks()
    {
        $data = TeamLeaderModel::banks();
        return $this->success($data);
    }

    /**
     * 设置提现账户
     *
     * @RequestMapping(path="/v1/api/team_lader/withdrawal_account/{id:\d+}", methods="get,put")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function setWithdrawalAccount(int $id, RequestInterface $request)
    {
        try {
            $filed = ['account_name', 'account_bank', 'bank_card_number'];
            if ($request->isMethod('get')) {
                $info = $this->teamLeaderService->getInfoById($id, $filed);
                return $this->success($info['data'] ?? [], '获取提现信息成功');
            }
            $data = $request->inputs($filed);
            $rules = [
                'account_name' => 'required',
                'account_bank' => 'required|int',
                'bank_card_number' => 'required',
            ];
            $message = [
                'account_name.required' => '请设置开户人',
                'account_bank.required' => '请设置开户行',
                'account_bank.int' => '请选择正确的开户行',
                'bank_card_number.required' => '请设置银行卡号',
            ];
            return $this->settingValidator($id, $data, $rules, $message);
        } catch (\Exception $e) {
            return $this->failed($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 设置营业时间
     *
     * @RequestMapping(path="/v1/api/team_lader/business_hours/{id:\d+}", methods="get,put")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function setBusinessHours(int $id, RequestInterface $request)
    {
        try {
            $filed = [
                'status',
                Db::raw('left(opening_time,5) as opening_time'),
                Db::raw('left(closing_time,5) as closing_time')
            ];
            if ($request->isMethod('get')) {
                $info = $this->teamLeaderService->getInfoById($id, $filed);
                return $this->success($info['data'] ?? [], '获取营业时间成功');
            }
            $data = $request->inputs(['status', 'opening_time', 'closing_time']);
            $rules = [
                'status' => [
                    'required',
                    Rule::in([3, 4])
                ],
                'opening_time' => 'required',
                'closing_time' => 'required|after:opening_time',
            ];
            $message = [
                'status.required' => '请设置营业状态',
                'opening_time.required' => '请设置开门营业时间',
                'closing_time.required' => '请设置关门营业时间',
            ];
            if ((strtotime($data['closing_time']) - strtotime($data['opening_time'])) < 3600) {
                throw new \Exception('营业时间不能小于 60 分钟');
            }
            if (in_array($data['status'], [3, 4])) {
                // 更改最后营业时间
                $data['last_business_hours'] = time();
            }
            return $this->settingValidator($id, $data, $rules, $message);
        } catch (\Exception $e) {
            return $this->failed($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 设置 自定义校验
     *
     * @param $id
     * @param $data
     * @param $rules
     * @param $message
     * @return array
     * @throws \Exception
     */
    public function settingValidator($id, $data, $rules, $message)
    {
        $validator = $this->validationFactory->make($data, $rules, $message);
        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new \Exception($errorMessage, ErrorCode::PARAMS_INVALID);
        }
        $res = $this->teamLeaderService->setting($id, $data);
        if (!$res) {
            throw new \Exception('设置失败', ErrorCode::SYSTEM_INVALID);
        }
        $this->teamLeaderService->delRedisData('resourceRedis', 'nearShop-crd');
        return $this->success('', '操作成功');
    }

    /**
     * 佣金明细
     *
     * @RequestMapping(path="/v1/api/team_lader/commission_records/{id:\d+}", methods="get")
     *
     * @param int $id
     * @return array
     */
    public function commission_records(int $id)
    {
        $filed = [
            Db::raw('concat(if(income > 0,\'+\',\'-\'),round(if(income > 0,income,expend) / 100,2)) as change_money'),
            Db::raw('if(type = 1,"提现",if(type=2,"订单收益","订单退款")) as type'),
            Db::raw('IFNULL(order_no,"") as order_no'),
            Db::raw('if(type = 1 and withdraw_status = 0,"审核中",ROUND(balance / 100,2)) as balance'),
            'created_at',
        ];
        $res = $this->teamLeaderService->commissionRecords($id, $filed);
        if ($res) {
            $data = $res->items();
            $total = $res->total();
        }
        return $this->success(($data ?? []), '获取佣金明细成功', ($total ?? 0));
    }

    /**
     * 单天的订单数据统计
     *
     * @RequestMapping(path="/v1/api/team_lader/order_data_single_day/{id:\d+}", methods="get")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function getOneDayOrderData(int $id, RequestInterface $request)
    {
        $date = $request->input('date');
        if (!$date) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $info = $this->teamLeaderService->getDayWriteOffOrder($id, $date);
        return $this->success($info, '获取单天的订单数据统计成功');
    }

    /**
     * 区间的订单数据统计
     * @RequestMapping(path="/v1/api/team_lader/order_data_interval/{id:\d+}", methods="get")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function getIntervalOrderData(int $id, RequestInterface $request)
    {
        $type = $request->input('type');
        if (!$type) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        // 1 :'七天',2 : '近30天',3 : '上月;
        // 默认 七天
        $start_date = date('Y-m-d 00:00:00', strtotime('-7 day'));
        $end_date = date('Y-m-d 23:59:59');
        if ($type == 2) {
            $start_date = date('Y-m-d 00:00:00', strtotime('-30 day'));
            $end_date = date('Y-m-d 23:59:59');
        }
        if ($type == 3) {
            $start_date = date('Y-m-01 00:00:00', strtotime('last month'));
            $end_date = date('Y-m-d 23:59:59', strtotime(date('Y-m-1') . '-1 day'));
        }
        $dates = $this->teamLeaderService->prDates($start_date, $end_date);
        $info = $this->teamLeaderService->getDayWriteOffOrder($id, $dates);
        return $this->success($info, '获取区间的订单数据统计成功');
    }

    /**
     * 核销
     *
     * @RequestMapping(path="/v1/api/team_lader/write_off/{id:\w+}", methods="get,put")
     *
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function writeOff(int $id, RequestInterface $request)
    {
        $code = $request->input('code');
        if (!$code) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        if ($request->isMethod('get')) {
            $info = $this->teamLeaderService->scanCodeGetOrderInfo($id, $code);
            if (!$info['success']) {
                return $this->failed(ErrorCode::PARAMS_INVALID, $info['msg']);
            }
            return $this->success($info['data'], '获取佣金明细成功');
        }
        $order_no = $request->input('order_no');
        if (!$order_no) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $list = $request->input('list');
        if (!$list) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $res = $this->teamLeaderService->writeOff($id, $order_no, json_decode($list, true));
        if ($res['code']) {
            return $this->failed($res['code'], $res['msg'] ?: null);
        }
        return $this->success([], '核销成功');
    }

    /**
     *
     * order_status =1 全部 2待自提 3已完成 4已退款
     *  团长订单
     * @RequestMapping(path="/v1/api/team_lader/order/{id:\d+}", methods="get")
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function order(int $id, RequestInterface $request)
    {
        $param = $request->all();
        $perPage = !empty($param['perpage']) ? $param['perpage'] : 10;
        if (!$param['order_status'] || empty($id)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }

        $filed = [
            'order_no',
            'create_at',
            'order_commission',
            'total_price',
            'goods_price',
            'write_off_code',
            'status',
            'leader_id'
        ];
        $order = $this->teamLeaderService->teamOrder($filed, $param, $id, (int)$perPage);
        return $this->success($order->items(), '获取成功', $order->total());
    }
    /**
     *
     *
     * 订单详情
     * @RequestMapping(path="/v1/api/team_lader/order/detail", methods="get")
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function orderDetail(RequestInterface $request)
    {
        $param = $request->all();
        if (!$param['order_no'] || empty($param['leader_id'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $orderDetail = $this->teamLeaderService->teamOrderDetail((string)$param['order_no'], (int)$param['leader_id']);
        return $this->success($orderDetail, '获取成功');
    }

    /**
     * 后台提现记录列表
     * @RequestMapping(path="/v1/teamLeader/withdraw", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param RequestInterface $request
     *
     * @return array
     */
    public function withdrawList(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['*'];
        $res = $this->teamLeaderService->withdrawList($params, $perPage, $field);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 后台提现记录详情
     * @RequestMapping(path="/v1/teamLeader/withdraw/{id:\d+}", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id
     *
     * @return array
     */
    public function withdrawInfo(int $id)
    {
        $field = ['*'];
        $res = $this->teamLeaderService->withdrawInfo($id, $field);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 提现审核（审核只有通过操作）
     * @PutMapping(path="/v1/teamLeader/withdraw/approve", methods="put")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param int $id   提现申请 ID
     *
     * @return array
     */
    public function withdrawApprove(RequestInterface $request)
    {
        $params = $request->all();
        if (!$params['id']) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        if (!$params['withdraw_certificate']) {
            return $this->failed(ErrorCode::WITHDRAW_CERTIFICATE_INVALID);
        }
        $res = $this->teamLeaderService->withdrawApprove($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }


    /*
     *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
     *                                                *团长数据分析*                                                      *
     *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
     */


    /**
     * 次日达店铺中心--团长实时交易情况
     * @RequestMapping(path="/v1/teamLeader/realTimeTransactions", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function realTimeTransactions()
    {
        $today = Carbon::today()->toDateString();   // 2020-12-03
        $yesterday = Carbon::yesterday()->toDateString();   // 2020-12-02

        // 今日团长数量
        $res[0]['today_teamLeader_num'] = $this->teamLeaderService->getTeamLeaderNum($today);
        // 昨日团长数量
        $res[0]['yesterday_teamLeader_num'] = $this->teamLeaderService->getTeamLeaderNum($yesterday);

        //今日活跃团长
        $res[0]['today_active_teamLeader_num'] = $this->teamLeaderService->getActiveTeamLeaderNum($today);
        //昨日活跃团长
        $res[0]['yesterday_active_teamLeader_num'] = $this->teamLeaderService->getActiveTeamLeaderNum($yesterday);

        //今日核销订单金额
        $res[0]['today_order_write_off_amount'] = $this->teamLeaderService->orderWriteOffAmount($today);
        //昨日核销订单金额
        $res[0]['yesterday_order_write_off_amount'] = $this->teamLeaderService->orderWriteOffAmount($yesterday);

        //今日团长佣金合计
        $res[0]['today_commission_of_the_leader'] = $this->teamLeaderService->commissionOfTheLeader($today);
        //昨日团长佣金合计
        $res[0]['yesterday_commission_of_the_leader'] = $this->teamLeaderService->commissionOfTheLeader($yesterday);

        //团长可提现佣金合计
        $res[0]['withdrawable_commission'] = $this->teamLeaderService->withdrawableCommission();
        //团长提现中佣金合计
        $res[0]['commission_in_withdrawal'] = $this->teamLeaderService->commissionInWithdrawal();

        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res, '操作成功');
        }
    }

    /**
     * 次日达店铺中心--销售订单走势图
     * @RequestMapping(path="/v1/teamLeader/salesOrderTrend", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function salesOrderTrend()
    {
        $res = $this->teamLeaderService->salesOrderTrend();
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 次日达店铺中心--团长销售额排名 TOP 20
     * @RequestMapping(path="/v1/teamLeader/leaderSalesRanking", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function leaderSalesRanking()
    {
        $res = $this->teamLeaderService->leaderSalesRanking();
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 次日达店铺中心--销售商品排名 TOP 20
     * @RequestMapping(path="/v1/teamLeader/commoditySalesRanking", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function commoditySalesRanking()
    {
        $res = $this->teamLeaderService->commoditySalesRanking();
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 店铺数据报表
     * @RequestMapping(path="/v1/teamLeader/storeDataReport", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function storeDataReport(RequestInterface $request)
    {
        $params = $request->all();
        $res = $this->teamLeaderService->storeDataReport($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 店铺数据报表详情 -- 团长订单
     * @RequestMapping(path="/v1/teamLeader/storeDataReportDetails/order", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function storeDataReportDetailsWithOrder(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['*'];
        $res = $this->teamLeaderService->storeDataReportDetailsWithOrder($params, $perPage, $field);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 小程序团长中心配送单列表
     * @RequestMapping(path="/v1/api/team_lader/deliverlist", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function deliverList(RequestInterface $request)
    {
        $params = $request->all();
        $leader_id = $params['leader_id'];
        $status = $params['status'];
        if (empty($leader_id) || empty($status)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->teamLeaderService->deliverList($leader_id, $status);
        if (!$res) {
            return $this->failed(ErrorCode::LEADER_ERROR);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 店铺数据报表详情 -- 团长提现记录
     * @RequestMapping(path="/v1/teamLeader/storeDataReportDetails/Withdrawal", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function storeDataReportDetailsWithWithdrawal(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['*'];
        $res = $this->teamLeaderService->storeDataReportDetailsWithWithdrawal($params, $perPage, $field);
        if (!$res['code']) {
            return $this->success($res['data']->items(), '获取成功', $res['data']->total());
        } else {
            return $this->failed($res['code']);

        }
    }

    /**
     * 小程序团长中心配送单详情
     * @RequestMapping(path="/v1/api/team_lader/deliverdetails", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function deliverDetails(RequestInterface $request)
    {
        $params = $request->all();
        $leader_id = $params['leader_id'];
        $times = $params['time'];
        if (empty($leader_id)||empty($times)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $res = $this->teamLeaderService->deliverDetails($leader_id,$times);
        if (!$res) {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        } else {
            return $this->success($res, '操作成功');
        }
    }

    /**
     * 店铺实时数据
     * @RequestMapping(path="/v1/teamLeader/storeRealTimeData", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function storeRealTimeData(RequestInterface $request)
    {
        $params = $request->all();
        $res = $this->teamLeaderService->getStoreRealTimeData($params);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 次日达店铺详情--团长实时交易情况
     * @RequestMapping(path="/v1/teamLeader/shopWithRealTimeTransactions", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function shopWithRealTimeTransactions(RequestInterface $request)
    {
        $shopId = $request->input('shop_id');
        if(!$shopId){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入店铺编码');
        }
        $today = Carbon::today()->toDateString();
        $yesterday = Carbon::yesterday()->toDateString();

        $res['code'] = 0;
        // 今日团长数量
        $res[0]['today_teamLeader_num'] = $this->teamLeaderService->getTeamLeaderNum($today, $shopId);
        // 昨日团长数量
        $res[0]['yesterday_teamLeader_num'] = $this->teamLeaderService->getTeamLeaderNum($yesterday, $shopId);

        //今日活跃团长
        $res[0]['today_active_teamLeader_num'] = $this->teamLeaderService->getActiveTeamLeaderNum($today, $shopId);
        //昨日活跃团长
        $res[0]['yesterday_active_teamLeader_num'] = $this->teamLeaderService->getActiveTeamLeaderNum($yesterday, $shopId);

        $todayData = $this->shop->getDateShopWriteTrading($today, $shopId, 1);
        $yesterdayData = $this->shop->getDateShopWriteTrading($yesterday, $shopId, 1);
        //今日核销订单金额
//        $res[0]['today_order_write_off_amount'] = $todayData['amount'];
//        //昨日核销订单金额
//        $res[0]['yesterday_order_write_off_amount'] = $yesterdayData['amount'];

        //今日核销订单金额
        $res[0]['today_order_write_off_amount'] = $this->teamLeaderService->orderWriteOffAmount($today, $shopId);
        //昨日核销订单金额
        $res[0]['yesterday_order_write_off_amount'] = $this->teamLeaderService->orderWriteOffAmount($yesterday, $shopId);

        //今日团长佣金合计
        $res[0]['today_commission_of_the_leader'] = $todayData['commission'];
        //昨日团长佣金合计
        $res[0]['yesterday_commission_of_the_leader'] = $yesterdayData['commission'];

        //团长可提现佣金合计
        $res[0]['withdrawable_commission'] = $this->teamLeaderService->withdrawableCommission($shopId);
        //团长冻结金额合计
        $res[0]['frozen_amount'] = $this->teamLeaderService->frozenAmount($shopId);

        if (!$res['code']) {
            return $this->success($res, '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 次日达店铺详情--销售订单走势图
     * @RequestMapping(path="/v1/teamLeader/salesOrderTrendByShop", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function salesOrderTrendByShop(RequestInterface $request)
    {
        $shopId = $request->input('shop_id');
        if(!$shopId){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入店铺编码');
        }

        $res = $this->teamLeaderService->salesOrderTrend($shopId);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 团长详情--团长实时交易情况
     * @RequestMapping(path="/v1/teamLeader/RealTimeOfTeamLeader", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function realTimeOfTeamLeader(RequestInterface $request)
    {
        $leaderId = $request -> input('leader_id');
        if(!$leaderId){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入团长 ID');
        }
        $today = Carbon::today()->toDateString();
        $yesterday = Carbon::yesterday()->toDateString();

        // 待分拣
        $res[0]['today_sorting'] = $this->teamLeaderService->getQuantityToBeSorted($leaderId)['today'];
        $res[0]['yesterday_sorting'] = $this->teamLeaderService->getQuantityToBeSorted($leaderId)['yesterday'];

        // 待核销
        $res[0]['today_to_be_written_off'] = $this->teamLeaderService->getLeaderToBeWrittenOffNum($today, $leaderId);
        $res[0]['yesterday_to_be_written_off'] = $this->teamLeaderService->getLeaderToBeWrittenOffNum($yesterday, $leaderId);

        // 核销订单金额
//        $res[0]['today_order_write_off_amount'] = $this->teamLeaderService->LeaderOrderWriteOffAmount($today, $leaderId) ?? '0.00';
//        $res[0]['yesterday_order_write_off_amount'] = $this->teamLeaderService->LeaderOrderWriteOffAmount($yesterday, $leaderId) ?? '0.00';

        // 核销订单金额
        $todayData = $this -> shop -> getDateShopWriteTrading($today, $leaderId, 2);
        $yesterdayData = $this -> shop -> getDateShopWriteTrading($yesterday, $leaderId, 2);
//        $res[0]['today_order_write_off_amount'] = $this->teamLeaderService->getDateShopWriteTrading($today, $leaderId) ?? '0.00';
        $res[0]['today_order_write_off_amount'] = $todayData['amount'];
        $res[0]['yesterday_order_write_off_amount'] = $yesterdayData['amount'];

        // 团长佣金合计
        $res[0]['today_total_commission'] = $todayData['commission'];
        $res[0]['yesterday_total_commission'] = $yesterdayData['commission'];

        // 团长可提现佣金合计
        $res[0]['total_withdrawable_commission'] = $this->teamLeaderService->totalWithdrawableCommissionByLeader($leaderId) ?? '0.00';
        // 团长冻结佣金合计
        $res[0]['total_frozen_commission'] = $this->teamLeaderService->totalFrozenCommissionByLeader($leaderId) ?? '0.00';

        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res, '操作成功');
        }

    }

    /**
     * 团长详情--销售订单走势图
     * @RequestMapping(path="/v1/teamLeader/salesOrderTrendByLeader", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function salesOrderTrendByLeader(RequestInterface $request)
    {
        $leaderId = $request->input('leader_id');
        if(!$leaderId){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入团长 ID');
        }

        $res = $this->teamLeaderService->salesOrderTrend(null, $leaderId);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data'], '操作成功');
        }
    }

    /**
     * 团长详情--团长订单
     * @RequestMapping(path="/v1/teamLeader/leaderOrder", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function leaderOrder(RequestInterface $request)
    {
        $params = $request->all();
        if(!$params['leader_id']){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入团长 ID');
        }
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['*'];
        $res = $this->teamLeaderService->leaderOrder($params, $perPage, $field);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']->items(), '操作成功',$res['data']->total());
        }
    }

    /**
     * 团长详情--团长提现记录
     * @RequestMapping(path="/v1/teamLeader/WithdrawalRecordOfLeader", methods="get")
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array
     */
    public function WithdrawalRecordOfLeader(RequestInterface $request)
    {
        $params = $request->all();
        if(!$params['leader_id']){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请传入团长 ID');
        }
        $perPage = isset($params['perpage']) ? (int)($params['perpage']) : 15;
        $field = ['*'];
        $res = $this->teamLeaderService->WithdrawalRecordOfLeader($params, $perPage, $field);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']->items(), '操作成功',$res['data']->total());
        }
    }

}
